package cn.kow.kmall.controller;

import cn.kow.kmall.common.util.ItemUtils;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.core.util.MoneyUtils;
import cn.kow.kmall.pojo.dto.CartItemAddDTO;
import cn.kow.kmall.pojo.dto.CartItemDTO;
import cn.kow.kmall.pojo.dto.CartItemUpdateDTO;
import cn.kow.kmall.pojo.dto.ItemCardDTO;
import cn.kow.kmall.pojo.entity.CartItem;
import cn.kow.kmall.pojo.entity.Sku;
import cn.kow.kmall.pojo.vo.CartGroupVO;
import cn.kow.kmall.pojo.vo.CartInfoVO;
import cn.kow.kmall.pojo.vo.CartItemVO;
import cn.kow.kmall.service.CartService;
import cn.kow.kmall.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-05-13 15:27
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/list")
    public KmallResult listCart(@RequestAttribute Long uid) {
        List<CartItem> cartItemList = cartService.listItem(uid);
        List<CartGroupVO> groupVOList = new ArrayList<>();
        int itemNum = 0;
        int totalPrice = 0;
        boolean allChecked = true;
        if (!CollectionUtils.isEmpty(cartItemList)) {
            List<Long> skuIds = cartItemList.stream().map(i -> i.getSkuId()).collect(Collectors.toList());

            List<ItemCardDTO> itemList = itemService.listItemCardBySkuIds(skuIds);
            Map<Long, ItemCardDTO> itemMap = itemList.stream().collect(Collectors.toMap(ItemCardDTO::getSkuId, s -> s));
            List<CartItemVO> cartItemVOList = new ArrayList<>(cartItemList.size());
            List<CartItemVO> invalidItemList = new ArrayList<>(cartItemList.size());
            for (CartItem cartItem : cartItemList) {
                Long skuId = cartItem.getSkuId();
                int num = cartItem.getItemNum();
                CartItemVO cartItemVO = new CartItemVO();
                cartItemVO.setItemId(cartItem.getItemId());
                cartItemVO.setSkuId(cartItem.getSkuId());
                cartItemVO.setItemNum(num);
                cartItemVO.setChecked(cartItem.getChecked());
                ItemCardDTO item = itemMap.get(skuId);

                if (item != null) {
                    cartItemVO.setSellingPrice(MoneyUtils.Fen2YuanStr(item.getSellingPrice()));
                    cartItemVO.setItemName(item.getItemName());
                    cartItemVO.setItemImage(item.getItemImage());
                    cartItemVO.setItemSpec(item.getItemSpec());
                    cartItemVOList.add(cartItemVO);
                    if (!cartItem.getChecked()) {
                        allChecked = false;
                    } else {
                        itemNum += num;
                        totalPrice += (item.getSellingPrice() * num);
                    }
                } else {
                    cartItemVO.setSellingPrice(MoneyUtils.Fen2YuanStr(cartItem.getSellingPrice()));
                    cartItemVO.setItemName(cartItem.getItemName());
                    cartItemVO.setItemImage(cartItem.getItemPic());
                    cartItemVO.setItemSpec(cartItem.getItemSpec());
                    cartItemVO.setChecked(false);
                    invalidItemList.add(cartItemVO);
                }
            }
            CartGroupVO defaultGroup = new CartGroupVO();
            defaultGroup.setPromId(0L);
            defaultGroup.setPromType(null);
            defaultGroup.setItemList(cartItemVOList);
            groupVOList.add(defaultGroup);

            CartGroupVO invalidGroup = new CartGroupVO();
            invalidGroup.setPromId(0L);
            invalidGroup.setPromType(null);
            invalidGroup.setItemList(invalidItemList);
            groupVOList.add(invalidGroup);
        }

        List<String> policyList = (List<String>) redisTemplate.opsForValue().get("policy");
        CartInfoVO cartInfoVO = new CartInfoVO();
        cartInfoVO.setItemCount(cartItemList.size());
        cartInfoVO.setItemNum(itemNum);
        cartInfoVO.setAllChecked(allChecked);
        cartInfoVO.setTotalPrice(MoneyUtils.Fen2YuanStr(totalPrice));
        cartInfoVO.setPolicyDescList(policyList);
        cartInfoVO.setCartGroupList(groupVOList);
        return KmallResult.success(cartInfoVO);
    }


    @PostMapping(value = "/save")
    public KmallResult saveCartItem(@RequestAttribute Long uid, @RequestBody CartItemAddDTO itemAddDTO) {
        Long skuId = itemAddDTO.getSkuId();
        Sku sku = itemService.getSkuById(skuId);
        CartItemDTO itemDTO = new CartItemDTO();
        BeanUtils.copyProperties(sku, itemDTO);

        BeanUtils.copyProperties(itemAddDTO, itemDTO);
        itemDTO.setUid(uid);
        itemDTO.setItemNum(itemAddDTO.getItemNum());
        itemDTO.setChecked(true);
        itemDTO.setItemPic(sku.getSkuPic());
        itemDTO.setItemSpec(ItemUtils.formatSkuSpecName(sku.getSkuSpecName()));
        cartService.saveItem(itemDTO);
        return KmallResult.success();
    }

    @PostMapping(value = "/update")
    public KmallResult updateCartItem(@RequestAttribute Long uid, @RequestBody CartItemUpdateDTO itemUpdateDTO) {
        itemUpdateDTO.setUid(uid);
        cartService.updateItem(itemUpdateDTO);
        return KmallResult.success();
    }

    @GetMapping(value = "/delete")
    public KmallResult delete(@RequestAttribute Long uid, @RequestParam Long[] skuIds) {
        cartService.deleteItem(uid, Arrays.asList(skuIds));
        return listCart(uid);
    }

    @GetMapping(value = "/selectAll")
    public KmallResult updateCheck(@RequestAttribute Long uid, @RequestParam boolean checked) {
        cartService.updateCheck(uid, checked);
        return KmallResult.success();
    }
}
